package iot

import (
	"errors"
	"gorm.io/gorm"
	"iot-base/common/dbobj"
)

type (
	Stations dbobj.Station

	StationMode struct {
		db *gorm.DB
	}
)

func NewStationMode(db *gorm.DB) *StationMode {
	return &StationMode{
		db,
	}
}

func (s *StationMode) Update(ID string, value interface{}) error {
	return s.db.Model(&Stations{}).Where("uid = ?", ID).Updates(value).Error
}

func (s *StationMode) Delete(ID string) error {
	return s.db.Where("uid = ?", ID).Delete(&Stations{}).Error
}

func (s *StationMode) FindGroupStationCount(uuid, sName string, ids []int64) (int64, error) {
	var count int64
	dbSession := s.db.Model(&Stations{}).Joins("JOIN auth_group_stations ON stations.uid = auth_group_stations.station_id AND auth_group_stations.group_id in ?", ids)
	if uuid != "" {
		dbSession.Where("stations.uid = ?", uuid)
	}
	if sName != "" {
		dbSession.Where("stations.s_name like ?", sName+"%")
	}
	err := dbSession.Count(&count).Error
	if err != nil {
		return count, err
	}
	return count, nil
}

func (s *StationMode) FindGroupStationList(ids []int64, uuid, sName string, page, size int) ([]Stations, error) {
	station := make([]Stations, 0, 1)
	dbSession := s.db.Model(&Stations{}).Joins("JOIN auth_group_stations ON stations.uid = auth_group_stations.station_id AND auth_group_stations.group_id in ?", ids)
	dbSession.Limit(size).Offset((page - 1) * size)
	dbSession.Order("auth_group_stations.id desc")
	if uuid != "" {
		dbSession.Where("stations.uid = ?", uuid)
	}
	if sName != "" {
		dbSession.Where("stations.s_name like ?", sName+"%")
	}
	err := dbSession.Find(&station).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return station, nil
	} else if err != nil {
		return station, err
	}
	return station, nil
}

func (s *StationMode) FindCount(uuid, sName string) (int64, error) {
	var count int64
	dbSession := s.db.Model(&Stations{})
	if uuid != "" {
		dbSession.Where("uid = ?", uuid)
	}
	if sName != "" {
		dbSession.Where("s_name like ?", sName+"%")
	}
	err := dbSession.Count(&count).Error
	if err != nil {
		return count, err
	}
	return count, nil
}

func (s *StationMode) FindList(uuid, sName string, page, size int) ([]Stations, error) {
	station := make([]Stations, 0, 1)
	dbSession := s.db.Model(&Stations{})
	dbSession.Limit(size).Offset((page - 1) * size)
	if uuid != "" {
		dbSession.Where("uid = ?", uuid)
	}
	if sName != "" {
		dbSession.Where("s_name like ?", sName+"%")
	}
	err := dbSession.Find(&station).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return station, nil
	} else if err != nil {
		return station, err
	}
	return station, nil
}

func (s *StationMode) CountStationChild(stationId string) (int64, error) {
	var total int64
	err := s.db.Model(&Stations{}).Where("parent_id = ?", stationId).Count(&total).Error
	return total, err
}
